/**
 * 京东联盟签名生成模块
 * @file 生成京东联盟API请求签名及调试信息
 * @version 1.0.0
 * @author uniapp云对象
 * @see {@link https://open.jd.com/home/home#/api/apiList 京东联盟API文档}
 */

const { normalizePayload, buildSignParams, buildJdSign } = require('./@utils')

/**
 * 生成京东联盟签名及调试信息
 * @param {object} payload 请求参数
 * @param {object} [payload.auth] 认证信息
 * @param {string} payload.method API方法名称
 * @param {object} [payload.businessParams] 业务参数
 * @returns {{sign: string, params: object, rawStr: string, sortedKeys: string[]}}
 * @example
 * // 新格式
 * generateSign({
 *   method: 'jd.union.open.goods.rank.query',
 *   businessParams: { rankId: 1 }
 * })
 *
 * // 旧格式（兼容）
 * generateSign({
 *   appKey: 'xxx',
 *   appSecret: 'xxx',
 *   method: 'jd.union.open.goods.rank.query'
 * })
 */
function generateSign(payload) {
  // 兼容新旧格式
  let finalPayload
  if (payload.auth || payload.query || payload.options) {
    const { auth, options } = normalizePayload(payload)
    finalPayload = {
      appKey: auth.appKey,
      appSecret: auth.appSecret,
      accessToken: auth.accessToken,
      method: payload.method,
      businessParams: payload.businessParams,
      systemParams: payload.systemParams,
      timestamp: options.timestamp,
      version: options.version,
      format: options.format,
      signMethod: options.signMethod
    }
  } else {
    finalPayload = payload
  }

  const { params, appSecret } = buildSignParams(finalPayload)
  const { sign, rawStr, sortedKeys } = buildJdSign(appSecret, params)
  return {
    sign,
    params,
    rawStr,
    sortedKeys
  }
}

module.exports = generateSign
